#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import glob
import math
import optparse
import os
import os.path
import re
import subprocess
import sys
import time
from re import sub

"""
Expected input is of format
[FRAME NUMBER][WHITESPACE][TEXT]

SRT-file is generated with [FRAME NUMBER]+4 seconds with 4 second duration.
Chapters-file uses exactly the specified time calculated from frame numbers. 
"""

#~ 'Main'
if __name__ == "__main__":
    if len( sys.argv ) < 2:
        print( "Gimme a file to work on!" )
        sys.exit( 2 )
    # Process input file.
    inFile = sys.argv[-1]
    srtFile = os.path.splitext( inFile )[0] + ".srt"
    chapFile = os.path.splitext( inFile )[0] + ".chapters"
    print( "Generating subtitles file '%s'" % srtFile )
    print( "Generating chapters file '%s'" % chapFile )
    srtFile = open( srtFile, "w" )
    chapFile = open( chapFile, "w" )
    subsLineCount = 1
    for line in open( inFile, "r" ):
        parts = line.split()
        # Get frame number.
        frames = int( parts.pop( 0 ) )
        # Restore rest into a string.
        rest = ' '.join( parts )
        # Get exact start time as seconds.
        theTime = frames / 25.0
        # Get exact start time's fractions.
        theTimeMillisecs = ( "%f" % math.fmod( theTime, 1 ) )[2:5]
        # Similar calculations to subtitle start time.
        startTime = theTime + 4.0
        startMillisecs = ( "%f" % math.fmod( startTime, 1 ) )[2:5]
        # Similar calculations to subtitle end time.
        endTime = startTime + 4.0
        endMillisecs = ( "%f" % math.fmod( endTime, 1 ) )[2:5]
        # Generate time format strings.
        theTimeString = time.strftime( "%H:%M:%S", time.gmtime( theTime ) ) + ":%s" % theTimeMillisecs
        subsStartTime = time.strftime( "%H:%M:%S", time.gmtime( startTime ) ) + ":%s" % startMillisecs
        subsEndTime = time.strftime( "%H:%M:%S", time.gmtime( endTime ) ) + ":%s" % endMillisecs
        # Print lines out to SRT-file.
        print( subsLineCount, file = srtFile )
        print( subsStartTime, "-->", subsEndTime, file = srtFile )
        print( rest + "\n", file = srtFile )
        # Print lines out to chapters-file.
        print( "CHAPTER%d=%s" % ( subsLineCount, theTimeString ), file = chapFile )
        print( "CHAPTER%d=%s" % ( subsLineCount, rest ), file = chapFile )
        # Increment subtitle/chapter counter.
        subsLineCount += 1
    print( "All done, TTFN." )
